package com.example.project10;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 书籍列表管理Activity - 重构版
 * 使用MVVM架构，降低耦合度
 */
public class BookListActivity extends AppCompatActivity {

    private EditText etBookNumber, etBookName;
    private Button btnAdd, btnDelete, btnUpdate, btnQuery;
    private RecyclerView recyclerView;
    private BookAdapter bookAdapter;
    private List<Book> bookList;
    
    private BookViewModel viewModel;
    private String userEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);

        // 获取用户邮箱
        userEmail = getIntent().getStringExtra("user_email");
        if (userEmail == null) {
            Toast.makeText(this, "用户信息错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(BookViewModel.class);
        viewModel.initialize(this, userEmail);

        // 初始化视图
        initViews();

        // 设置点击事件
        setClickListeners();

        // 初始化RecyclerView
        initRecyclerView();

        // 观察ViewModel数据变化
        observeViewModel();
    }

    private void initViews() {
        etBookNumber = findViewById(R.id.et_book_number);
        etBookName = findViewById(R.id.et_book_name);
        
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        recyclerView = findViewById(R.id.recycler_view);

        // 设置标题
        Toolbar toolbar = findViewById(R.id.toolbar_book_list);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("我的书籍");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
    
    private void setClickListeners() {
        btnAdd.setOnClickListener(v -> viewModel.addBook());
        btnDelete.setOnClickListener(v -> confirmDeleteBook());
        btnUpdate.setOnClickListener(v -> showUpdateDialog());
        btnQuery.setOnClickListener(v -> viewModel.searchBooks());
        
        // 设置输入框的文字变化监听
        etBookNumber.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                viewModel.setBookNumber(s.toString());
            }
            
            @Override
            public void afterTextChanged(android.text.Editable s) {}
        });
        
        etBookName.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                viewModel.setBookName(s.toString());
            }
            
            @Override
            public void afterTextChanged(android.text.Editable s) {}
        });
    }

    private void initRecyclerView() {
        bookList = new ArrayList<>();
        bookAdapter = new BookAdapter(bookList, this::onBookItemClick);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(bookAdapter);
    }
    
    /**
     * 观察ViewModel数据变化
     */
    private void observeViewModel() {
        // 观察书籍列表变化
        viewModel.getBookList().observe(this, books -> {
            if (books != null) {
                updateBookList(books);
            }
        });
        
        // 观察选中的书籍变化
        viewModel.getSelectedBook().observe(this, book -> {
            // 更新Adapter的选中状态
            if (book == null) {
                bookAdapter.clearSelection();
            }
        });
        
        // 观察消息变化
        viewModel.getMessage().observe(this, message -> {
            if (message != null && !message.isEmpty()) {
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
            }
        });
        
        // 观察输入字段变化
        viewModel.getBookNumber().observe(this, bookNumber -> {
            if (!etBookNumber.getText().toString().equals(bookNumber)) {
                etBookNumber.setText(bookNumber);
            }
        });
        
        viewModel.getBookName().observe(this, bookName -> {
            if (!etBookName.getText().toString().equals(bookName)) {
                etBookName.setText(bookName);
            }
        });
    }

    /**
     * 确认删除书籍
     */
    private void confirmDeleteBook() {
        Book selectedBook = viewModel.getCurrentSelectedBook();
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要删除的书籍", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除书籍《" + selectedBook.getBookName() + "》吗？")
                .setPositiveButton("确定", (dialog, which) -> viewModel.deleteSelectedBook())
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 显示修改对话框
     */
    private void showUpdateDialog() {
        Book selectedBook = viewModel.getCurrentSelectedBook();
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要修改的书籍", Toast.LENGTH_SHORT).show();
            return;
        }
        
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_update_book, null);
        EditText etUpdateBookNumber = dialogView.findViewById(R.id.et_update_book_number);
        EditText etUpdateBookName = dialogView.findViewById(R.id.et_update_book_name);
        
        // 设置当前值
        etUpdateBookNumber.setText(selectedBook.getBookNumber());
        etUpdateBookName.setText(selectedBook.getBookName());

        new AlertDialog.Builder(this)
                .setTitle("修改书籍信息")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String newBookNumber = etUpdateBookNumber.getText().toString().trim();
                    String newBookName = etUpdateBookName.getText().toString().trim();
                    viewModel.updateSelectedBook(newBookNumber, newBookName);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 更新书籍列表
     */
    private void updateBookList(List<Book> books) {
        bookList.clear();
        bookList.addAll(books);
        bookAdapter.notifyDataSetChanged();
        bookAdapter.clearSelection(); // 清除选择状态
    }

    /**
     * 书籍项点击事件
     */
    private void onBookItemClick(Book book, int position) {
        // 通知ViewModel选中了书籍
        viewModel.setSelectedBook(book);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}